package com.jiuyin.dianjing.watcher;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Text input box special character filtering
 *
 * @author Administrator
 */
public class MoneyFormatWatcher implements TextWatcher {
    private final static int STRING_LENGTH = 3;
    /**
     * Listen to changes the text box
     */
    private EditText editText;
    private String point;

    public MoneyFormatWatcher(String point, EditText editText) {
        this.editText = editText;
        this.point = point;
    }

    @Override
    public void onTextChanged(CharSequence ss, int start, int before, int count) {
        String editable = editText.getText().toString();
        String str = stringFilterText(editable);
        if (str.contains(point)) {
            String strDecimal = str.substring(str.indexOf(point));
            if (strDecimal.length() > STRING_LENGTH) {
                str = str.substring(0, str.indexOf(point) + 3);
            }
        }
        if (!editable.equals(str)) {
            editText.setText(str);
            editText.setSelection(str.length());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    /**
     * edittext Filter only number and .
     */
    private String stringFilterText(String str) throws PatternSyntaxException {
        String regEx = "[^0-9.,]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
}